import java.text.DecimalFormat; class MatrixLib { // Method to read a matrix of integers, of specified dimension. public static int[][] readIntMatrix( int numRows, int numCols ) { int row; // row index int col; // column index int[][] matrix; // result matrix = new int[numRows][numCols]; System.out.println( "Enter a matrix, one row at a time" ); System.out.print( "for " + numRows + " rows, with " ); System.out.println( numCols + " entries per row: "); for ( row = 0; row < numRows; row = row + 1 ) { matrix[row] = ITI1120.readIntLine( ); } return matrix; } // Method to read a matrix of doubles, of specified dimension. public static double[][] readDoubleMatrix( int numRows, int numCols ) throws java.io.IOException { int row; // row index int col; // column index double[][] matrix; // result matrix = new double[numRows][numCols]; System.out.println( "Enter a matrix, one row at a time" ); System.out.print( "for " + numRows + " rows, with " ); System.out.println( numCols + " entries per row: "); for ( row = 0; row < numRows; row = row + 1 ) { matrix[row] = ITI1120.readDoubleLine( ); } return matrix; } // Method to print a matrix of integers with nice formatting. public static void printMatrix( int[][] matrix ) { int row; // row index int col; // column index for ( row = 0; row < matrix.length; row = row + 1 ) { // Print entries in row for ( col = 0; col < matrix[row].length; col = col + 1 ) { System.out.print( format( matrix[row][col] ) + " " ); } System.out.println( ); } } // This method takes a value of type int, and returns a String // that contains the value of the int, but formatted to have width // of exactly 5 characters. // Use: get numbers to line up in columns public static String format( int value ) { String result; DecimalFormat df; int numBlanks; // The following requests numeric output with exactly one decimal // place, and at least one but no more than two digits to the left // of the decimal point. See java.text.DecimalFormat. df = new DecimalFormat( "####0" ); // The next line actually does the formatting, and produces a String. result = df.format( value ); // The following makes sure that the String has exactly 5 characters // (needed to space columns evenly) and adds blanks to the front if // needed. Class DecimalFormat ought to do this, but... numBlanks = 5 - result.length( ); for ( int index = 1; index <= numBlanks; index++ ) { result = " " + result; } return result; } }